/*
 * @Descripttion: 
 * @version: 
 * @Author: LEO
 * @Date: 2021-05-08 13:08:50
 * @LastEditors: 871387321@qq.com 871387321@qq.com
 * @LastEditTime: 2023-11-15 17:10:49
 */
import React, { useRef, useCallback, useEffect, useState, useMemo } from 'react';
import { PageHeader, Formx, Button, history, units } from '@library';
import { FormxRefProps } from '@library/components/formx/interface';
import Qs from 'query-string';
import WfView from '../../../components/wfView/WfView';
import FormView from '../../../components/formView/FormView';
import { FormxControlTypes as FCT } from '@library';
import Role from './_Role';
import { WF_STATUS } from '../data';
import { db } from '@library'
import { WorkFlowHeadProps } from '../../../interface';
import i18n from "@library/app/i18n";


const i18NT = window.$app.t, required = true;


const DetailsPage = () => {
  const formxRef = useRef<FormxRefProps>(null);
  const query = Qs.parseUrl(window.location.href).query;
  const [details, setDetails] = useState<WorkFlowHeadProps>({} as any);
  const [formId, setFormId] = useState('');
  const [formList, setFormList] = useState<any>([])

  useEffect(() => {
    db.getForms().then(result => {
      if (result) {
        setFormList(result)
      }
    });
  }, []);

  useEffect(() => {
    if (query.id) {
      db.getWorkflow(query.id).then(result => {
        if (result) {
          setDetails(result);
          setFormId(result.formId);
        }
      });
    }
  }, [query.id]);

  const onSave = useCallback(async () => {
    const formData = await formxRef.current?.validateFields();

    if (formData) {
      if (formData.formId && formList) {
        formData.formName = (formList.find(item => item.id == formData.formId))?.formName
      }
      const result = await db.saveWorkflow({
        ...formData as WorkFlowHeadProps,
      });

      if (result) {
        if (!formData.id) {
          history.replace('/mymodel/details?id=' + result.id);
          return;
        }

        units.message.success();
        setDetails(result);
      }
    }
  }, [formList]);

  const onPub = useCallback(async () => {
    const formData = await formxRef.current?.validateFields();

    if (formData) {
      const result = await db.publishWorkflow({
        ...details,
        ...formData,
        status: WF_STATUS.PUB
      } as WorkFlowHeadProps);

      if (result) {
        units.message.success();
        history.push('/mymodel');
      }
    }
  }, [details]);

  const onWithdraw = useCallback(async () => {
    const result = await db.withdrawWorkflow(details.id as string);
    if (result) {
      units.message.success();
      history.push('/mymodel');
    }
  }, [details.id]);

  const toEditWf = useCallback(() => {
    history.push('/mymodel/details/workflow?id=' + details.id);
  }, [details.id]);

  const onValuesChange = useCallback((value, allValue) => {
    setFormId(allValue.formId);

    let extra: any = {};

    setDetails(prev => ({ ...prev, ...allValue, ...value, ...extra }));
  }, []);

  const formItems = useMemo(() => [
    { name: 'workflowName', required, label: i18NT('workflowName') },
    {
      name: 'formId',
      label: i18NT('/form'),
      type: FCT.SELECT,
      required,
      options: {
        fieldNames: { label: "formName", value: 'id' },
        dataSource: formList
      }
    },
  ], [query.id, formList]);

  return (
    <>
      <PageHeader extra={
        <>
          {!details.status && <Button.Save onClick={onSave} />}
          {details.status === WF_STATUS.NEW && (
            <>
              <Button.Save type='default' onClick={onSave} />
              <Button.Submit onClick={onPub}>{window.$app.t('statusRelease')}</Button.Submit>
            </>
          )}
          {details.status === WF_STATUS.PUB && (
            <Button onClick={onWithdraw}>{window.$app.t('withdraw')}</Button>
          )}
        </>
      } />
      <div className='common-scroll-view'>
        <div className='common-block'>
          <PageHeader title='baseInfo' />
          <Formx
            disabled={details.status === WF_STATUS.PUB}
            onValuesChange={onValuesChange}
            initialValues={details}
            ref={formxRef}
            formItems={formItems} />
        </div>

        <div className='common-block'>
          <PageHeader title='bpmnContent' extra={
            details.status === WF_STATUS.NEW && <Button onClick={toEditWf}>
              {window.$app.t('editWorkflow')}
            </Button>
          } />
          <WfView flat bpmnContent={details.bpmnContent} />
        </div>

        {formId && (
          <div className='common-block'>
            <PageHeader title='formDesign' />
            <FormView disabled isLformHtml formId={formId} />
          </div>
        )}

        {details.id && <Role disabled={details.status === WF_STATUS.PUB} workflowId={details.id} />}
      </div>
    </>
  );
};

export default DetailsPage